/*
 * @Author: Dufen~123 dufen.0
 * @Date: 2024-11-26 15:28:40
 * @LastEditors: Dufen~123 dufen.0
 * @LastEditTime: 2024-11-26 15:45:42
 * @FilePath: \my-app\src\store\reducers\tab.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { createSlice } from "@reduxjs/toolkit";
//这是一个方法，里面传一些参数，然后创建一个切片对象。每一个reducer都有一个对应的切片对象
//ruducer是state的整合器，redux用来把一个或多个reducer封装成store
const tabSlice = createSlice({
  name: "tab", //reducer的名字，
  initialState: {
    isCollapse: false,
    tabList: [{ path: "/home", name: "home", label: "首页" }],
    currentMenu: { path: "/home", name: "home", label: "首页" },
  },
  reducers: {
    //写对state的各种操作
    //菜单的折叠与展开
    CollapseMenu: (state) => {
      state.isCollapse = !state.isCollapse;
    },
    //点击菜单改变tabList
    selectMenuList: (state, { payload: val }) => {
      // payload是传给这个reducer的其他参数，也就是aside组件传过来的，上面解构出来并命名为val
      state.currentMenu = val;
      //判断tag是否存在，如果遇到已近存在的tag就不需要添加
      const result = state.tabList.findIndex((item) => item.name === val.name); //val是当前点击的菜单项，item是遍历tabList的项
      // console.log('result',result)
      if (result === -1) {
        //result为-1就是不存在，遇到不存在的tag就添加
        state.tabList.push(val);
        // console.log('val',val)
      }
    },
    //关闭面包屑，点击删除从tabList中删除当前项
    closeTab: (state, { payload: val }) => {
      const result = state.tabList.findIndex((item) => item.name == val.name);
      state.tabList.splice(result, 1);
      //删除完当前项之后高亮往前移一个
      if (result > 0) {
        state.currentMenu = state.tabList[result - 1];
      }
    },
    //点击标签改变currentMenu
    changeCurrentMenu: (state, { payload: val }) => {
      state.currentMenu = val;
    },
  },
});
//把reducer中的具体action解构出来
export const { CollapseMenu, selectMenuList, closeTab, changeCurrentMenu } =
  tabSlice.actions;
export default tabSlice.reducer;
